﻿using Sidvall.Collections;
using Sidvall.Serialization;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Principal;

namespace Sidvall.Web.Security
{
    public class AuthenticationMethodValidator : ValidatorBase
    {
        #region Public Members

        #region AuthenticationMethod

        private string _AuthenticationMethod;
        public string AuthenticationMethod
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(_AuthenticationMethod))
                    return _AuthenticationMethod;
                return Sidvall.Web.SystemContext.Current.RequiredAuthenticationMethod;
            }
            set
            {
                _AuthenticationMethod = value;
            }
        }

        #endregion

        #region IsValid

        public bool IsValid(IIdentity identity, NameValueCollection formValues)
        {
            if (IsIgnored(identity, formValues))
                return true;
            if (!string.IsNullOrWhiteSpace(this.AuthenticationMethod))
            {
                var value = this.ClaimManager.FindClaimValue(identity, Sidvall.Security.ClaimTypes.AuthenticationMethodReference);
                if (string.IsNullOrWhiteSpace(value))
                {
                    var identityToken = GetIdentityToken(identity, formValues);
                    if (identityToken != null)
                        value = identityToken.AuthenticationMethods.JoinToString(",", true);
                }
                if (!this.AuthenticationMethod.Equals(value, false, System.StringComparison.OrdinalIgnoreCase))
                    return false;
            }
            return true;
        }

        #endregion

        #endregion
        #region Constructors

        public AuthenticationMethodValidator()
        {
        }
        public AuthenticationMethodValidator(string authenticationMethod)
            : this(authenticationMethod, null)
        {
        }
        public AuthenticationMethodValidator(string authenticationMethod, IEnumerable<string> ignoredUsers)
            : base(ignoredUsers)
        {
            this.AuthenticationMethod = authenticationMethod;
        }

        #endregion
    }
}
